package main

import (
	"fmt"
	"runtime"
	"runtime/debug"
)

func main() {
	printStackSize("main start")
	// 递归 5 000 次，每次 2 KB 局部数组，强制扩栈
	var f func(int)
	f = func(d int) {
		var buf [2048]byte
		_ = buf
		if d > 0 {
			f(d - 1)
		}else {
			printStackSize("reach bottom")
		}
	}
	f(5000)
	printStackSize("main end")
}

func printStackSize(when string) {
	var m runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&m)
	fmt.Printf("%s  StackInUse=%.2f MB\n", when, float64(m.StackInuse)/1024/1024)
	fmt.Printf("       当前栈底片段:\n%s\n\n", debug.Stack()[:200])
}
